package com.qk.state.persist;

import com.qk.enums.ClueEvent;
import com.qk.enums.ClueState;
import com.qk.mapper.ClueMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.statemachine.StateMachineContext;
import org.springframework.statemachine.StateMachinePersist;
import org.springframework.statemachine.persist.DefaultStateMachinePersister;
import org.springframework.statemachine.persist.StateMachinePersister;
import org.springframework.statemachine.support.DefaultStateMachineContext;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 状态机持久化配置
 * @author 28188
 */
@Configuration
public class StateMachinePersisterConfig {

    private final ClueMapper clueMapper;

    public StateMachinePersisterConfig(ClueMapper clueMapper) {
        this.clueMapper = clueMapper;
    }

    @Bean
    public StateMachinePersister<ClueState, ClueEvent, String> persister() {
        StateMachinePersist<ClueState, ClueEvent, String> persist = new StateMachinePersist<>() {
            // 内存存储
            private final Map<String, ClueState> store = new ConcurrentHashMap<>();

            /**
             * 持久化状态机状态到内存
             */
            @Override
            public void write(StateMachineContext<ClueState, ClueEvent> context, String key) {
                store.put(key, context.getState());
            }

            /**
             * 恢复状态机状态
             */
            @Override
            public StateMachineContext<ClueState, ClueEvent> read(String key) {
                ClueState state = store.get(key);

                // 如果内存没有，从数据库读取
                if (state == null) {
                    int stateInt = clueMapper.selectStateById(key); // 你自己实现的方法，返回 ClueState
                    state = ClueState.fromCode(stateInt);
                }

                if (state == null) {
                    // 如果数据库也没有，使用初始状态 UNASSIGNED
                    state = ClueState.UNASSIGNED;
                }

                return new DefaultStateMachineContext<>(state, null, null, null, null, key);
            }
        };

        return new DefaultStateMachinePersister<>(persist);
    }
}
